#include <QDir>
#include <QScrollArea>
#include <QVBoxLayout>
#include <QToolButton>
#include <QToolBar>
#include <QComboBox>
#include <QDebug>

#include "hahawindow.h"
#include "haha_global.h"
#include "pagegenerator.h"
#include "displayitem.h"
#include "hahapageparser.h"
#include "imagecontainer.h"
#include "../imagedownloader.h"
#include "../utils.h"

namespace Haha
{
class HahaWindowPrivate
{
public:
    QList<DisplayItem*> displayItems;
    QScrollArea* scrollArea;
    ImageContainer* container = nullptr;
    QToolButton* prevButton = nullptr;
    QToolButton* nextButton = nullptr;
    QToolButton* clearButton = nullptr;
    QComboBox* categoryCombo = nullptr;
};

HaHaWindow::HaHaWindow(QWidget *parent) : QWidget(parent)
{
    QDir hahaDir(Haha::Constant::HAHASAVEDIR);
    if (!hahaDir.exists())
        hahaDir.mkdir(Haha::Constant::HAHASAVEDIR);

    d_ptr = new HahaWindowPrivate;

    QVBoxLayout* layout = new QVBoxLayout;
    QToolBar* bar = new QToolBar(this);
    layout->addWidget(bar);
    d_ptr->prevButton = new QToolButton(this);
    d_ptr->prevButton->setAutoRaise(true);
    d_ptr->prevButton->setIcon(QIcon(":/images/previous.png"));
    bar->addWidget(d_ptr->prevButton);

    d_ptr->nextButton = new QToolButton(this);
    d_ptr->nextButton->setAutoRaise(true);
    d_ptr->nextButton->setIcon(QIcon(":/images/next.png"));
    bar->addWidget(d_ptr->nextButton);

    d_ptr->clearButton = new QToolButton(this);
    d_ptr->clearButton->setAutoRaise(true);
    d_ptr->clearButton->setIcon(QIcon(":/images/clear.png"));
    bar->addWidget(d_ptr->clearButton);
    bar->addSeparator();

    d_ptr->categoryCombo = new QComboBox(this);
    d_ptr->categoryCombo->addItem(tr("New"), PageGenerator::New); // default is New, so put it there first
    d_ptr->categoryCombo->addItem(tr("Good"), PageGenerator::Good);
    bar->addWidget(d_ptr->categoryCombo);

    d_ptr->container = new ImageContainer(this);

    d_ptr->scrollArea = new QScrollArea(this);
    d_ptr->scrollArea->setWidget(d_ptr->container);
    layout->addWidget(d_ptr->scrollArea);

    setLayout(layout);

    connect(d_ptr->prevButton, SIGNAL(pressed()), this, SLOT(showPreviousPage()));
    connect(d_ptr->nextButton, SIGNAL(pressed()), this, SLOT(showNextPage()));
    connect(d_ptr->clearButton, SIGNAL(pressed()), d_ptr->container, SLOT(clear()));
    connect(d_ptr->categoryCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onCategoryChanged(int)));
}

HaHaWindow::~HaHaWindow()
{
    delete d_ptr;
}

void HaHaWindow::showNextPage()
{
    qDeleteAll(d_ptr->displayItems);
    Haha::PageGenerator* pg = Haha::PageGenerator::instance();
    QUrl url = pg->next();

    Jcr::HahaPageParser* hpp = new Jcr::HahaPageParser();
    hpp->setUrl(url);
    connect(hpp, SIGNAL(finished()), this, SLOT(onPageLoaded()));
    hpp->run();

    d_ptr->prevButton->setEnabled(false);
    d_ptr->nextButton->setEnabled(false);
}

void HaHaWindow::showPreviousPage()
{
    qDeleteAll(d_ptr->displayItems);

    Haha::PageGenerator* pg = Haha::PageGenerator::instance();
    QUrl url = pg->next();

    Jcr::HahaPageParser* hpp = new Jcr::HahaPageParser();
    hpp->setUrl(url);
    connect(hpp, SIGNAL(finished()), this, SLOT(onPageLoaded()));
    hpp->run();

    d_ptr->prevButton->setEnabled(false);
    d_ptr->nextButton->setEnabled(false);
}

void HaHaWindow::onPageLoaded()
{
    d_ptr->nextButton->setEnabled(true);
    d_ptr->prevButton->setEnabled(true);

    Jcr::HahaPageParser* hpp = qobject_cast<Jcr::HahaPageParser*>(sender());
    QList<QUrl> imgs = hpp->images();
    QString imgPath;
    foreach (auto img, imgs) {

        imgPath = QString(img.toString());
//        if (!Jcr::Utils::isGif(QUrl(imgPath))) {
//            qDebug() << "Got non gif url: " << imgPath << ", ignore.";
//            continue;
//        }

        QFileInfo fi(img.toString());
        Jcr::ImageDownloader* id = new Jcr::ImageDownloader(img, Haha::Constant::HAHASAVEDIR);
//        connect(id, SIGNAL(finished()), id, SLOT(deleteLater()));
        id->setSaveName(fi.baseName());

        if (QFile::exists(id->localPath())) {
            qDebug() << "already got this one.";
            Haha::DisplayItem* di = new Haha::DisplayItem(QUrl(id->localPath()));
            di->setRemoteUrl(QUrl(imgPath));
            d_ptr->container->addItem(di);
            delete id;
            continue;
        } else {
            qDebug() << "now, downloading :" << imgPath;
        }

        connect(id, SIGNAL(finished()), this, SLOT(onImageLoaded()));
        id->run();
    }
}

void HaHaWindow::onImageLoaded()
{
    Jcr::ImageDownloader* id = qobject_cast<Jcr::ImageDownloader*>(sender());
    Haha::DisplayItem* di = new Haha::DisplayItem(QUrl(id->localPath()));
    di->setRemoteUrl(id->url());
    d_ptr->container->addItem(di);
}

void HaHaWindow::onCategoryChanged(int index)
{
    QVariant v = d_ptr->categoryCombo->itemData(index);
    PageGenerator::instance()->setCategory(static_cast<PageGenerator::Category>(v.toInt()));
}

} // namespace haha
